package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ConfigConstant;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.constants.ServiceUrlConst;
import com.authine.cloudpivot.ext.dto.quotation.QuotationGoodsApprovedHistoryDto;
import com.authine.cloudpivot.ext.dto.quotation.QuotationGoodsDto;
import com.authine.cloudpivot.ext.enums.commoditymaterials.GoodsPurchaseTypeEnum;
import com.authine.cloudpivot.ext.enums.inquiry.InquiryStatusEnum;
import com.authine.cloudpivot.ext.enums.inquiry.QuotationStatusEnum;
import com.authine.cloudpivot.ext.fun.ObjectFunction;
import com.authine.cloudpivot.ext.utils.BoResultFormat;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.cloudpivot.ext.utils.HttpClients;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.system.SessionUser;
import com.authine.cloudpivot.ext.utils.system.UserUtils;
import com.authine.common.util.DateUtils;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.query.expression.Operator;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName CheckPriceService
 * @Description: 我的核价
 * @Author fj
 * @Date 2021/5/2
 * @Version V1.0
 **/
@Path("CheckPriceService")
@Slf4j
public class CheckPriceService extends ApplicationService {
    private static final NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);
    private static final QuotationService quotationService = new QuotationService();

    /**
     * 客户还价
     *
     * @param approvedHistoryDto 还价信息
     * @return 响应结果
     */
    @Path("approveBack")
    @POST
    @Operation(summary = "客户还价", tags = CUSTOM_SERVICE)
    public SingleResponse<BO> approveBack(@Parameter QuotationGoodsApprovedHistoryDto approvedHistoryDto) {
        if (approvedHistoryDto.getQuotationIdList() == null || approvedHistoryDto.getQuotationIdList().isEmpty()) {
            return SingleResponse.error("-1", "报价商品id为空");
        }
//        if (approvedHistoryDto.getCounterPriceDate() == null) {
//            return SingleResponse.error("-2", "还价截止日期为空");
//        }
        if (approvedHistoryDto.getCounterPrePrice() == null) {
            return SingleResponse.error("-3", "还价价格(未税)为空");
        }
        if (StringUtils.isEmpty(approvedHistoryDto.getReason())) {
            return SingleResponse.error("-4", "还价理由为空");
        }
        SingleResponse<BOList> quotationList = BoServiceUtils.findListByIn(ModelConst.T_QUOTATION_GOODS, "id", approvedHistoryDto.getQuotationIdList());
        log.info("------------------------通过报价商品id获取报价商品信息列表：{}------------------------", JSONObject.toJSONString(quotationList));
        if (quotationList.getData().getTotal() == 0) {
            return SingleResponse.error("-5", "数据库未获取到您要还价的商品信息");
        }
        Map<String, Object> quotationMap;
        List<Map<String, Object>> approvedHistoryList = new ArrayList<>();
        for (Map<String, Object> quotation : quotationList.getData().getData()) {
            quotationMap = Maps.newHashMap();
            if (!QuotationStatusEnum.QUOTATION_3_QUOTED.getCode().equals(quotation.get("quotation_goods_status"))) {
                return SingleResponse.error("-6", "只能是已报价中的商品才可以还价");
            }
            if (QuotationStatusEnum.QUOTATION_5_PICKETED.getCode().equals(quotation.get("quotation_goods_status"))) {
                return SingleResponse.error("-7", "已关闭的询价无法还价");
            }
            quotationMap.put("id", quotation.get("id"));
            quotationMap.put("quotation_goods_status", QuotationStatusEnum.QUOTATION_4_APPROVE_BACK.getCode());
            // 还价时同步还价理由、还价截止日期、还价价格到报价表中
            quotationMap.put("approved_failed_reason", approvedHistoryDto.getReason());
            quotationMap.put("counter_price_date", approvedHistoryDto.getCounterPriceDate());
            quotationMap.put("counter_pre_price", approvedHistoryDto.getCounterPrePrice());
            SingleResponse<BO> quotationResult = BoServiceUtils.updateMainBo(ModelConst.T_QUOTATION_GOODS, quotationMap);
            log.info("------------------------报价商品更新成功，更新后结果：{}------------------------", JSONObject.toJSONString(quotationResult));
            if (quotationResult.isSuccess()) {
                approvedHistoryList.add(setApprovedHistory(approvedHistoryDto, quotation));
            }
        }
        SingleResponse<BO> approvedHistoryResult = BoServiceUtils.createBo(ModelConst.T_QUOTATION_GOODS_APP_HIS, approvedHistoryList);
        log.info("------------------------客户还价成功，还价结果：{}------------------------", JSONObject.toJSONString(approvedHistoryResult));
        return approvedHistoryResult;
    }

    /**
     * 客户定标
     *
     * @param quotationGoodsDto 报价商品信息
     * @return 响应结果
     */
    @Path("picketage")
    @POST
    @Operation(summary = "客户定标", description = "定标/一键定标/最低价定标", tags = CUSTOM_SERVICE)
    public SingleResponse<BO> picketage(@Parameter QuotationGoodsDto quotationGoodsDto) {
        if (quotationGoodsDto.getQuotationIdList() == null || quotationGoodsDto.getQuotationIdList().isEmpty()) {
            return SingleResponse.error("-1", "报价商品id为空");
        }
        String reason = StringUtils.isEmpty(quotationGoodsDto.getPicketageReason()) ? "最低价" : quotationGoodsDto.getPicketageReason();
        SingleResponse<BOList> quotationList = BoServiceUtils.findListByIn(ModelConst.T_QUOTATION_GOODS, "id", quotationGoodsDto.getQuotationIdList().stream().distinct().collect(Collectors.toList()));
        if (quotationList.getData().getTotal() == 0) {
            return SingleResponse.error("-2", "报价商品信息为空，请重新选择报价商品");
        }
        SingleResponse<BOList> goodsPurchaseResult;
        List<Map<String, Object>> inquiryResult;
        List<Map<String, Object>> inquiryGoodsAllResult;
        List<Map<String, Object>> inquiryGoodsResult;
        List<Map<String, Object>> quotationResult;
        Map<String, Object> inquiryGoodsMap;
        Map<String, Object> quotationMap;
        Map<String, Object> otherQuotationMap;
        Set<String> inquiryIdSet = Sets.newHashSet();
        String[] columns = new String[]{ConfigConstant.INQUIRY_GOODS_ID, ConfigConstant.QUOTATION_GOODS_STATUS};
        Operator[] operators = new Operator[]{Operator.EQ, Operator.EQ};
        String[] columnsVal = new String[3];
        columnsVal[1] = QuotationStatusEnum.QUOTATION_5_PICKETED.getCode();
        for (Map<String, Object> quotation : quotationList.getData().getData()) {
            // 判断组织采购表中是否有该报价商品
            goodsPurchaseResult = BoServiceUtils.findListBySimple(ModelConst.T_GOODS_PURCHASE, "quotation_goods_id", quotation.get("id"));
            if (goodsPurchaseResult.getData().getTotal() > 0) {
                return SingleResponse.error("-3", "定标失败，定标商品" + quotation.get("id") + "已存在");
            }
            // 获取报价商品对应的询价单信息
            inquiryResult = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY, "id", quotation.get("inquiry_id")).getData().getData();
            log.info("------------------------通过询价单id获取询价单列表：{}------------------------", JSONObject.toJSONString(inquiryResult));
            // 获取询价单下所有询价商品的信息
            inquiryGoodsAllResult = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY_GOODS, "inquiry_id", inquiryResult.get(0).get("id")).getData().getData();
            log.info("------------------------通过询价单id获取询价商品列表：{}------------------------", JSONObject.toJSONString(inquiryGoodsAllResult));
            if ("1".equals(inquiryResult.get(0).get("quote_total_strategy")) && "1".equals(inquiryResult.get(0).get("quote_multiple_purchases"))
                    && inquiryGoodsAllResult.size() != quotationList.getData().getTotal()) {
                return SingleResponse.error("-4", "该询价单询价，必须选择一家供应商进行一键定标");
            }
            if (DateUtils.parseDate(((String) quotation.get("expire"))).getTime() < System.currentTimeMillis()) {
                return SingleResponse.error("-5", "报价商品已过期");
            }
            // 获取报价商品对应的询价商品信息
            inquiryGoodsResult = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY_GOODS, "id", quotation.get("inquiry_goods_id")).getData().getData();
            String inquiryGoodsId = String.valueOf(inquiryGoodsResult.get(0).get("id"));
            if (InquiryStatusEnum.INQUIRY_GOODS_5_CLOSE.getCode().equals(inquiryGoodsResult.get(0).get("quotation_goods_status"))) {
                return SingleResponse.error("-6", "询价商品[" + inquiryGoodsId + "]状态为已关闭,无法定标");
            }
            // 通过询价单号查询已定标商品信息
            columnsVal[0] = inquiryGoodsId;
            int total = BoServiceUtils.findListByComplex(ModelConst.T_QUOTATION_GOODS, columns, columnsVal, operators).getData().getTotal();
            if (total > 0) {
                log.info("定标失败,原因该询价商品已经存在定标商品,不能重复定标" + "inquiryGoodsId：{}", inquiryGoodsId);
                return SingleResponse.error("-7", "询价商品[" + inquiryGoodsId + "]已经存在定标商品,不能重复定标");
            }
            quotationMap = Maps.newHashMap();
            quotationMap.put("id", quotation.get("id"));
            quotationMap.put("quotation_goods_status", QuotationStatusEnum.QUOTATION_5_PICKETED.getCode());
            quotationMap.put("picketage_reason", reason);
            quotationMap.put("picketage", true);
            // 更新报价商品状态为已定标
            BoServiceUtils.updateMainBo(ModelConst.T_QUOTATION_GOODS, quotationMap);

            inquiryIdSet.add(inquiryGoodsId);
            inquiryGoodsMap = Maps.newHashMap();
            inquiryGoodsMap.put("id", inquiryGoodsId);
            inquiryGoodsMap.put("inquiry_goods_status", InquiryStatusEnum.INQUIRY_GOODS_4_END.getCode());
            inquiryGoodsMap.put("picketaged", true);
            // 更新询价商品为已结束
            BoServiceUtils.updateMainBo(ModelConst.T_INQUIRY_GOODS, inquiryGoodsMap);
        }
        // todo 同步到es数据库

        // 通过询价商品id集合查询所有报价商品
        quotationResult = BoServiceUtils.findListByIn(ModelConst.T_QUOTATION_GOODS, "inquiry_goods_id", inquiryIdSet).getData().getData();
        if (quotationResult != null && !quotationResult.isEmpty()) {
            for (Map<String, Object> quo : quotationResult) {
                otherQuotationMap = Maps.newHashMap();
                if (!quotationGoodsDto.getQuotationIdList().contains(String.valueOf(quo.get("id")))) {
                    if (QuotationStatusEnum.QUOTATION_0_NEW.getCode().equals(quo.get("quotation_goods_status"))) {
                        //参与但是没有提交状态改为已终止，主要为了和已关闭区分
                        otherQuotationMap.put("quotation_goods_status", QuotationStatusEnum.QUOTATION_7_TERMINATION.getCode());
                    } else {
                        otherQuotationMap.put("quotation_goods_status", QuotationStatusEnum.QUOTATION_6_CLOSE.getCode());
                    }
                    otherQuotationMap.put("id", quo.get("id"));
                    BoServiceUtils.updateMainBo(ModelConst.T_QUOTATION_GOODS, otherQuotationMap);
                }
            }
        }
        // 存入物料报价库
        SingleResponse<BO> result = quotationGoodsToPurchaseGoods(quotationGoodsDto.getQuotationIdList().stream().distinct().collect(Collectors.toList()));
        log.info("------------------------创建企业采购目录成功：{}------------------------", JSONObject.toJSONString(result));
        // todo 牧原定标，验证企业采购目录是否存在，存在的话，企业采购目录定标商品需要下架 禁用掉
        return result;
    }

    /**
     * 获取历史还价记录
     *
     * @param quotationGoodsDto 报价商品信息
     * @return 响应结果
     */
    @Path("getApproveHistoryList")
    @POST
    @Operation(summary = "获取历史还价记录", tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> getApproveHistoryList(@Parameter QuotationGoodsDto quotationGoodsDto) {
        Assert.notNull(quotationGoodsDto.getQuotationId(), "报价商品id不能为空");
        SessionUser sessionUser = new SessionUser();
        SingleResponse<BOList> quotationGoodsBOList;
        if (sessionUser.isPm()) {
            // 平台可以查看所有的还价记录
            quotationGoodsBOList = BoServiceUtils.findListBySimple(ModelConst.T_QUOTATION_GOODS_APP_HIS, "quotation_id", quotationGoodsDto.getQuotationId());
        } else {
            List<String> memberIdList = UserUtils.listSubMemberIds(sessionUser.get().getId());
            List<Map<String, Object>> result = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(memberIdList)) {
                StringBuilder sql = new StringBuilder();
                Map<String, Object> parameter = Maps.newHashMap();
                sql.append("select h.* from ")
                        .append(JdbcTemplateUtils.getTableName(ModelConst.T_QUOTATION_GOODS_APP_HIS)).append(" as h\n")
                        .append("left join ").append(JdbcTemplateUtils.getTableName(ModelConst.T_QUOTATION_GOODS)).append(" as qg on h.quotation_id = qg.id\n")
                        .append("left join ").append(JdbcTemplateUtils.getTableName(ModelConst.T_INQUIRY_GOODS)).append(" as ig on ig.id = qg.inquiry_goods_id\n")
                        .append("left join ").append(JdbcTemplateUtils.getTableName(ModelConst.T_INQUIRY)).append(" as i on i.id = ig.inquiry_id\n")
                        .append("where\n")
                        .append("JSON_UNQUOTE(i.member_id -> '$.id') in :memberListId\n")
                        .append("and qg.id = :id\n")
                        .append("order by h.createdTime desc\n");
                parameter.put("memberListId", memberIdList);
                parameter.put("id", quotationGoodsDto.getQuotationId());
                log.info("sql = {}, parameters = {}", sql, JSONObject.toJSONString(parameter));
                result = jdbcTemplate.queryForList(sql.toString(), parameter);
                log.info("--------------------通过报价商品id和会员id获取还价商品列表：{}--------------------", JSONObject.toJSONString(result));
                // 对结果进行格式化
                if (!CollectionUtils.isEmpty(result)) {
                    BoResultFormat.resultFormat(result, ModelConst.T_INQUIRY_GOODS, true);
                }
            }
            BOList boList = new BOList();
            boList.setSchemaCode(ModelConst.T_QUOTATION_GOODS_APP_HIS);
            boList.setData(CollectionUtils.isEmpty(result) ? Lists.newArrayList() : result);
            boList.setTotal(boList.getData().size());
            quotationGoodsBOList = SingleResponse.of(boList);
        }
        // 小规模供应商价格转换
        if (!CollectionUtils.isEmpty(quotationGoodsBOList.getData().getData())) {
            quotationService.conversion(quotationGoodsBOList.getData().getData());
        }
        return quotationGoodsBOList;
    }


    /**
     * 核退报价商品表数据赋值
     *
     * @param approvedHistoryDto 还价请求参数
     * @param quotation          报价商品数据
     * @return 还价商品
     */
    private Map<String, Object> setApprovedHistory(QuotationGoodsApprovedHistoryDto approvedHistoryDto, Map<String, Object> quotation) {
        Map<String, Object> approvedHistoryMap = Maps.newHashMap();
        approvedHistoryMap.put("approved_failed_reason", approvedHistoryDto.getReason());
        approvedHistoryMap.put("counter_price_date", approvedHistoryDto.getCounterPriceDate());
        approvedHistoryMap.put("counter_pre_price", approvedHistoryDto.getCounterPrePrice());
        approvedHistoryMap.put("org_category_name", quotation.get("org_category_name"));
        approvedHistoryMap.put("quotation_id", quotation.get("id"));
        approvedHistoryMap.put("name", quotation.get("name"));
        approvedHistoryMap.put("brand", quotation.get("brand"));
        approvedHistoryMap.put("model", quotation.get("model"));
        approvedHistoryMap.put("spec", quotation.get("spec"));
        approvedHistoryMap.put("price", quotation.get("price"));
        // todo 产品目前bug，需要手动解决，7.3版本修复
//        approvedHistoryMap.put("delivery", quotation.get("delivery") == null ? BigDecimal.ZERO : ((BigDecimal)quotation.get("delivery")).intValue());
        approvedHistoryMap.put("delivery", quotation.get("delivery"));
        approvedHistoryMap.put("num", quotation.get("num"));
        approvedHistoryMap.put("total", quotation.get("total"));
        approvedHistoryMap.put("unit", quotation.get("unit"));
        approvedHistoryMap.put("package_num", quotation.get("package_num"));
        approvedHistoryMap.put("package_unit", quotation.get("package_unit"));
        approvedHistoryMap.put("freight", quotation.get("freight"));
        approvedHistoryMap.put("taxRate", quotation.get("taxRate"));
        approvedHistoryMap.put("amount", quotation.get("amount"));
        approvedHistoryMap.put("expire", quotation.get("expire"));
        approvedHistoryMap.put("address", quotation.get("address"));
        approvedHistoryMap.put("attachment", quotation.get("attachment"));
        approvedHistoryMap.put("picketage", "1".equals(String.valueOf(quotation.get("picketage"))));
        approvedHistoryMap.put("description", quotation.get("description"));
        approvedHistoryMap.put("pretax_price", quotation.get("pretax_price"));
        approvedHistoryMap.put("pretax_total", quotation.get("pretax_total"));
        approvedHistoryMap.put("tax_payable", quotation.get("tax_payable"));
        approvedHistoryMap.put("pretax_freight", quotation.get("pretax_freight"));
        approvedHistoryMap.put("tax_payable_freight", quotation.get("tax_payable_freight"));
        approvedHistoryMap.put("tax_rate_freight", quotation.get("tax_rate_freight"));
        approvedHistoryMap.put("pretax_amount", quotation.get("pretax_amount"));
        return approvedHistoryMap;
    }

    /**
     * 根据报价商品id生成企业采购目录
     *
     * @param quotationIdList 报价商品id集合
     * @return 响应结果
     */
    @SuppressWarnings("unchecked")
    private SingleResponse<BO> quotationGoodsToPurchaseGoods(List<String> quotationIdList) {
        String[] columns = new String[]{"id", ConfigConstant.QUOTATION_GOODS_STATUS};
        Operator[] operators = new Operator[]{Operator.IN, Operator.EQ};
        Object[] columnsVal = new Object[]{quotationIdList, QuotationStatusEnum.QUOTATION_5_PICKETED.getCode()};
        SingleResponse<BOList> quotationResult = BoServiceUtils.findListByComplex(ModelConst.T_QUOTATION_GOODS, columns, columnsVal, operators);
        List<Map<String, Object>> inquiryResult;
        List<Map<String, Object>> inquiryGoodsResult;
        List<Map<String, Object>> purchaseGoodsData = new ArrayList<>();
        Map<String, Object> purchaseGoodsMap;
        //多组织数据转单组织数据
        ObjectFunction<SelectorFormat> multiToSingleSelectPerson = (a) -> {
            if (a != null) {
                return ((List<SelectorFormat>) a).get(0);
            }
            return null;
        };
        if (quotationResult.getData().getTotal() > 0) {
            for (Map<String, Object> quotation : quotationResult.getData().getData()) {
                purchaseGoodsMap = Maps.newHashMap();
                inquiryResult = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY, "id", quotation.get("inquiry_id")).getData().getData();
                inquiryGoodsResult = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY_GOODS, "id", quotation.get("inquiry_goods_id")).getData().getData();
                purchaseGoodsMap.put("type", "1".equals(String.valueOf(inquiryResult.get(0).get("quote_multiple_purchases"))) ? GoodsPurchaseTypeEnum.LOOP.getId() : GoodsPurchaseTypeEnum.SINGLE.getId());
                purchaseGoodsMap.put("quotation_goods_id", quotation.get("id"));
                purchaseGoodsMap.put("inquiry_id", quotation.get("inquiry_id"));
                purchaseGoodsMap.put("inquiry_goods_id", quotation.get("inquiry_goods_id"));
                purchaseGoodsMap.put("customer_id", ((List<SelectorFormat>) inquiryResult.get(0).get("organization_id")).get(0));
                purchaseGoodsMap.put("customer_name", inquiryResult.get(0).get("organization_company_name"));
                purchaseGoodsMap.put("vendor_id", ((List<SelectorFormat>) quotation.get("vendor_organization_id")).get(0));
                purchaseGoodsMap.put("vendor_name", quotation.get("vendor_organization_name"));
                purchaseGoodsMap.put("catalog", inquiryGoodsResult.get(0).get("platform_category_name"));
                purchaseGoodsMap.put("catalog_id", inquiryGoodsResult.get(0).get("category_id"));
                purchaseGoodsMap.put("brand", quotation.get("brand"));
                purchaseGoodsMap.put("name", quotation.get("name"));
                purchaseGoodsMap.put("model", quotation.get("model"));
                purchaseGoodsMap.put("spec", quotation.get("spec") == null ? "" : quotation.get("spec"));
                purchaseGoodsMap.put("unit", quotation.get("unit"));
                purchaseGoodsMap.put("package_unit", quotation.get("package_unit"));
                purchaseGoodsMap.put("package_num", quotation.get("package_num"));
                purchaseGoodsMap.put("customer_sku", inquiryGoodsResult.get(0).get("sku"));
                purchaseGoodsMap.put("customer_bar_code", inquiryGoodsResult.get(0).get("bar_code"));
                purchaseGoodsMap.put("vendor_sku", quotation.get("sku"));
                purchaseGoodsMap.put("vendor_bar_code", quotation.get("bar_code"));
                purchaseGoodsMap.put("golden_tax", "");
                purchaseGoodsMap.put("unspsc", "");
                purchaseGoodsMap.put("delivery", quotation.get("delivery"));

                purchaseGoodsMap.put("num", quotation.get("num"));
                purchaseGoodsMap.put("tax_rate", quotation.get("tax_rate"));
                purchaseGoodsMap.put("tax_rate_freight", quotation.get("tax_rate_freight"));
                purchaseGoodsMap.put("pretax_freight", quotation.get("pretax_freight"));
                purchaseGoodsMap.put("pretax_price", quotation.get("pretax_price"));
                purchaseGoodsMap.put("price", quotation.get("price"));
                purchaseGoodsMap.put("pretax_total", quotation.get("pretax_total"));
                purchaseGoodsMap.put("total", quotation.get("total"));
                purchaseGoodsMap.put("tax_payable", quotation.get("tax_payable"));
                purchaseGoodsMap.put("freight", quotation.get("freight"));
                purchaseGoodsMap.put("tax_payable_freight", quotation.get("tax_payable_freight"));
                purchaseGoodsMap.put("pretax_amount", quotation.get("pretax_amount"));
                purchaseGoodsMap.put("amount", quotation.get("amount"));

                purchaseGoodsMap.put("description", quotation.get("description"));
                purchaseGoodsMap.put("picketage_reason", quotation.get("picketage_reason"));
                purchaseGoodsMap.put("expire", quotation.get("expire"));

                purchaseGoodsMap.put("bought", BigDecimal.ZERO);
                purchaseGoodsMap.put("saled", true);
                purchaseGoodsMap.put("enabled", true);
                purchaseGoodsMap.put("del", false);
                purchaseGoodsMap.put("vmi_goods", !"0".equals(String.valueOf(inquiryResult.get(0).get("vmi_inquiry"))));
                purchaseGoodsMap.put("safety_stock_num", inquiryGoodsResult.get(0).get("safety_stock_num"));
                purchaseGoodsMap.put("maximum", quotation.get("maximum"));
                purchaseGoodsMap.put("min_order", Optional.ofNullable(quotation.get("min_order")).orElse(quotation.get("num")));
                if (new Double(purchaseGoodsMap.get("min_order").toString()) <= 0 || new Double(quotation.get("min_order").toString()).compareTo(new Double(purchaseGoodsMap.get("num").toString())) > 0) {
                    purchaseGoodsMap.put("min_order", quotation.get("num"));
                }
                // fixme 旭东需要的字段
                purchaseGoodsMap.put("inquiry_name", inquiryResult.get(0).get("name"));
                purchaseGoodsMap.put("demand_dept_id", multiToSingleSelectPerson.convert(inquiryResult.get(0).get("target_department_id")));
                purchaseGoodsMap.put("picketage_time", DateUtils.format2DateStr2(new Date()));
                purchaseGoodsMap.put("quote_total_strategy", "1".equals(String.valueOf(inquiryResult.get(0).get("quote_total_strategy"))));
                // fixme 冗余的字段
                String packageNum = quotation.get("package_num") == null ? BigDecimal.ZERO.toPlainString() : String.valueOf(((BigDecimal) quotation.get("package_num")).intValue());
                String packageUnit = quotation.get("package_unit") == null ? "" : "/" + quotation.get("package_unit") + "";
                purchaseGoodsMap.put("package", packageNum.concat(packageUnit));
                purchaseGoodsMap.put("area", inquiryGoodsResult.get(0).get("area"));
                purchaseGoodsMap.put("company", inquiryGoodsResult.get(0).get("company"));
                purchaseGoodsMap.put("warehouse", inquiryGoodsResult.get(0).get("warehouse"));

                // 解决企业采购目录成本中心不显示的问题
                purchaseGoodsMap.put("cost_center_id", inquiryResult.get(0).get("cost_center_id"));
                purchaseGoodsMap.put("cost_center_name", inquiryResult.get(0).get("cost_center_name"));
                purchaseGoodsData.add(purchaseGoodsMap);
            }
            log.info("------------------------purchaseGoodsData：{}------------------------", JSONObject.toJSONString(purchaseGoodsData));
            SingleResponse<BO> purchaseGoodsResult = BoServiceUtils.createBo(ModelConst.T_GOODS_PURCHASE, purchaseGoodsData);
            log.info("------------------------purchaseGoodsResult：{}------------------------", JSONObject.toJSONString(purchaseGoodsResult));
            log.info("发起定标流程calibration_approval_flow，企业采购单id::{}", purchaseGoodsResult.getData().getData().get("id"));
            String url = HttpClients.getUrl(AppConst.COMMODITYMATERIALS, ServiceUrlConst.APPROVAL_STARTWORKFLOWINSTANCE_URL);
            Map<String, Object> fileParam = Maps.newHashMap();
            fileParam.put("workflowCode", "calibration_approval_flow");
            fileParam.put("bizObjectId", purchaseGoodsResult.getData().getData().get("id"));
            fileParam.put("originator", RequestContext.getCorpLoginId());
            fileParam.put("departmentId", purchaseGoodsResult.getData().getData().get("createdDept").toString());
            String execute = HttpClients.execute(url, fileParam);
            log.info("返回结果::{}", JSON.toJSONString(execute));
            return purchaseGoodsResult;
        }
        return SingleResponse.error("-8", "报价商品对象保存失败");
    }
}
